package com.block.source.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.block.common.config.CommonConfig;
import com.block.common.constant.AppRspCodeConstant;
import com.block.common.constant.RedisKeyConstant;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.ISourceDataCallbackLogService;
import com.block.common.service.ISourceDataCountInfoService;
import com.block.common.vo.ResponseVo;
import com.block.db.entity.SourceMemberDataInfo;
import com.block.db.entity.SourcePushResultInfo;
import com.block.match.enums.OrderStatusEnum;
import com.block.match.model.dto.SourceRegisterResultDTO;
import com.block.match.service.IDataMatchOrderItemService;
import com.block.match.service.ISourceMatchHandleService;
import com.block.source.service.ISourceMemberDataInfoService;
import com.block.source.service.ISourcePushResultInfoService;
import com.block.source.service.ISourceResultHandleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.startup.StartupEndpoint;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.concurrent.TimeUnit;

@Service
public class SourceResultHandleService implements ISourceResultHandleService {

    @Autowired
    ISourceMatchHandleService sourceMatchHandleService;
    @Autowired
    ISourceDataCallbackLogService sourceDataCallbackLogService;
    @Autowired
    ISourceMemberDataInfoService sourceMemberDataInfoService;
    @Autowired
    IApplicationInfoService applicationInfoService;
    @Autowired
    IDataMatchOrderItemService dataMatchOrderItemService;
    @Autowired
    ISourceDataCountInfoService sourceDataCountInfoService;
    @Autowired
    NotifyExceptionService notifyExceptionService;
    @Autowired
    ISourcePushResultInfoService sourcePushResultInfoService;
    @Autowired
    CommonConfig commonConfig;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 机构订单推送
     *
     * @param resultNo
     * @return
     */
    @Override
    public ResponseVo approveToPush(String resultNo, String reqIp) {

        try {
            // 状态判断
            SourcePushResultInfo pushResultInfo = sourcePushResultInfoService.getById(resultNo);
            if (!StrUtil.equals(pushResultInfo.getStatus(), OrderStatusEnum.WAIT_PUSH.getValue())) {
                return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, "订单状态错误");
            }

            if (commonConfig.isSourceRegisterSingleIp()){
                // 只允许单ip进件
                String dateInfo = LocalDate.now().toString();
                String redisKey = StrUtil.format(RedisKeyConstant.SOURCE_REGISTER_IP_LIMIT, dateInfo, pushResultInfo.getChannelCode());

                Boolean isMember = stringRedisTemplate.opsForSet().isMember(redisKey, reqIp);
                if (isMember){
                    // 该ip 已经授权过了
                    SourcePushResultInfo updateEntity = new SourcePushResultInfo();
                    updateEntity.setId(pushResultInfo.getId());
                    updateEntity.setSettleStatus(OrderStatusEnum.IP_LIMIT.getValue());
                    updateEntity.setRegisterIp(reqIp);
                    sourcePushResultInfoService.updateById(updateEntity);
                    return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION, reqIp+";IP 授权限制");
                }
                stringRedisTemplate.opsForSet().add(redisKey, reqIp);
                stringRedisTemplate.expire(redisKey, 1L, TimeUnit.DAYS);
            }

            pushResultInfo.setRegisterIp(reqIp);
            // 执行推送到商户逻辑
            SourceRegisterResultDTO registerResultDTO = sourcePushResultInfoService.handlePushToMerchant(pushResultInfo);

            // 渠道方 跳转地址
            SourceMemberDataInfo memberDataInfo = sourceMemberDataInfoService.getById(pushResultInfo.getDataId());

            // 如果渠道方 跳转地址为空，则跳转线上地址
            String redirectUrl = memberDataInfo.getRedirectUrl();
            if (StrUtil.isEmpty(redirectUrl)) {
                redirectUrl = "https://h5.longzankeji.cn?ch=default";
            }

            JSONObject returnObject = new JSONObject();
            returnObject.put("redirectUrl", redirectUrl);

            return new ResponseVo(AppRspCodeConstant.SUCCESS, returnObject);
        } catch (Exception exception) {
            exception.printStackTrace();
            notifyExceptionService.notifyNoticeInfo("SOURCE_APPROVE_PUSH", "线索授权点击", "【resultNo】" + resultNo, exception);
        }
        return new ResponseVo(AppRspCodeConstant.SYS_EXCEPTION);
    }




}
